#include "list.h"


void init_list(node_t **root)
{
    if (*root != NULL)
        return;

    *root = malloc(sizeof(node_t));
    (*root)->data = NULL;
    (*root)->prev = NULL;
    (*root)->next = NULL;
}


node_t *insert_node(node_t *list, void *data)
{
    node_t *lk = malloc(sizeof(node_t));
    lk->data = data;
    lk->next = list->next;
    lk->prev = list;
    list->next = lk;
    
    if (lk->next != NULL)
        lk->next->prev = lk;
    
    return lk;
}


void delete_node(node_t *list, node_t **last)
{
    if (list->next == NULL)
    {
        list->prev->next = NULL;
        
        if (last != NULL)
            *last = list->prev;
    }
    else
    {
        list->next->prev = list->prev;
        list->prev->next = list->next;
    }

    free(list->data);
    list->data = NULL;

    free(list);
    list = NULL;
}


void delete_node_data(long size_data, void *data, node_t **root)
{
    node_t *iter;
    iter = *root;

    while (iter != NULL)
    {
        if (memcmp(iter->data, data, size_data) == 0)
        {
            delete_node(iter, NULL);
            return;
        }
        
        iter = iter->next;
    }
}


void free_list(node_t *root)
{
    // if (root->next == NULL)
    // {
    //     free(root->data);
    //     free(root);
    //     return;
    // }

    while (root != NULL)
    {
        if (root->next == NULL)
        {
            free(root->data);
            root->data = NULL;
            free(root);
            root = NULL;

            return;
        }

        free(root->data);
        root->data = NULL;

        root = root->next;

        free(root->prev);
        root->prev = NULL;
    }
}
